package softserve.vgolosh.tmn;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.AndFileFilter;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.NotFileFilter;
import org.apache.commons.io.filefilter.OrFileFilter;
import org.apache.commons.io.filefilter.PrefixFileFilter;

import softserve.vgolosh.utils.CmdUtil;

public class TMNUtilities {
	public static IOFileFilter DIRECTORY_FILTER = new AndFileFilter(
			DirectoryFileFilter.INSTANCE, new NotFileFilter(new OrFileFilter(
					new OrFileFilter(new PrefixFileFilter(".svn"),
							new PrefixFileFilter("spec")),
					new PrefixFileFilter("settings"))));

	static public TMNRegexFileFilter fileFilter = new TMNRegexFileFilter();

	public static List<TMN> createList(List<String> notes) {
		List<TMN> result = new ArrayList<TMN>();
		TMN note = null;
		String[] rs;
		for (String string : notes) {
			if (!string.startsWith("#")) {
				rs = string.split("\t\\|\\|\t");
				note = new TMN(rs[0], rs[1], rs[2]);
				result.add(note);
			}
		}
		return result;
	}

	public static TMNSearchResults search(String workingDir,
			List<String> clients, List<TMN> tmnList) {
		File dir = null;
		TMNSearchResults result = new TMNSearchResults();
		fileFilter.setTmnSearchResults(result);
		for (TMN tmn : tmnList) {
			fileFilter.setPattern(tmn.getFilesRegex());
			fileFilter.setSearchRegex(tmn.getSearchRegex());
			fileFilter.setCurrentTMN(tmn);
			for (String client : clients) {
				dir = new File(workingDir + client);
				fileFilter.setCurrentClient(client);
				FileUtils.listFiles(dir, fileFilter, DIRECTORY_FILTER);
			}
		}
		return result;
	}

	public static void openResultsInNotepad(String notepadLocation,
			List<TMNSearchResult> results) {
		File dir = new File(notepadLocation);
		String[] commands = null;
		for (TMNSearchResult tmnSearchResult : results) {
			commands = new String[] { "cmd.exe", "/c",
					"notepad++.exe " + tmnSearchResult.getFilePath() };
			CmdUtil.startCommand(commands, dir);
		}
	}
}
